package main

import (

	_ "cloud_worm/util/umodels"
	_ "cloud_worm/wormweb/routers"
	_ "cloud_worm/wormweb/controllers/ctrsecurity/crontask/taskset"
	"github.com/astaxie/beego"
	"cloud_worm/util/uconst"
	"fmt"
	"github.com/astaxie/beego/logs"
	"os"
	"cloud_worm/wormweb/controllers/ctrutil"
	"cloud_worm/wormweb/controllers/ctrinner/rpcbiz"
	"cloud_worm/util/unet/usocket"
	"cloud_worm/wormweb/controllers/ctrsecurity/crontask"

)

func main() {
	logs.Info("Start web server ......")

	// 初始化
	usocket.SetOpenFileLimit()
	logInit()
	httpAddrInit()
	setStaticRes()

	if err := rpcRun(); err != nil {
		panic(err)
		return
	}

	// TODO: 其他初始化待实现

	// 加载定时任务
	if err := crontask.InitLoadCronTask(); err != nil {
		logs.Notice(fmt.Sprintf("InitLoadCronTask: %s", err.Error()))
	}

	// 启动
	beego.Run()
	return
}

func rpcRun() error {
	rpcServe := rpcbiz.RpcServer{
		Address: fmt.Sprintf("%s:%s", ctrutil.LocalAddress, beego.AppConfig.String("rpc_port")),
		PemFile: beego.AppConfig.String("rpc_cert_file"),
		KeyFile: beego.AppConfig.String("rpc_key_file"),
	}
	logs.Info("%s", rpcServe)
	logs.Info(fmt.Sprintf("rpc server: (%s:%s)", ctrutil.LocalAddress, beego.AppConfig.String("rpc_port")))

	return rpcServe.RpcServe()
}

func setStaticRes() {
	beego.SetViewsPath("static")
	beego.SetStaticPath("/js", "static/js")
	beego.SetStaticPath("/css", "static/css")
	beego.SetStaticPath("/static", "static")
	return
}

// httpAddrInit 设置服务监听的端口，上线服务只监听内网端口
func httpAddrInit()  {
	if ctrutil.RunMode == uconst.RunModeLocalHost {
		return
	}

	httpEnable, err := beego.AppConfig.Bool("enable_http")
	if err != nil {
		logs.Error(fmt.Sprintf("`enable_http` error: %s", err.Error()))
	}
	httpsEnable, err := beego.AppConfig.Bool("enable_https")
	if err != nil {
		logs.Error(fmt.Sprintf("`enable_https` error: %s", err.Error()))
	}
	if httpsEnable == true {
		beego.BConfig.Listen.HTTPSAddr = ctrutil.LocalAddress
	} else if httpEnable == true {
		beego.BConfig.Listen.HTTPAddr = ctrutil.LocalAddress
	} else {
		beego.BConfig.Listen.HTTPAddr = ctrutil.LocalAddress
	}

	return
}

func logInit() {

	// 注意：只有线上分支，才日志级别提高
	if ctrutil.RunMode == uconst.RunModePub {
		// 生产环境
		beego.SetLevel(beego.LevelInformational)
		beego.SetLogFuncCall(true)

		// 生产环境，采用异步输出，提升性能; 异步输入出,增加缓存大小
		logs.Async(1024)

		// 设置日志的输出，以及日志文件处理方式
		logDir := "./logs/"
		_, err := os.Stat(logDir)
		if err != nil {
			err = os.Mkdir(logDir, 0755)
			if err == nil {
				// 创建成功
				logs.SetLogger(logs.AdapterFile, `{"filename": "logs/web.log", "maxlines":0,"maxsize":0,"daily":true,"maxdays":60}`)
			}
		} else {
			// logs目录存在
			logs.SetLogger(logs.AdapterFile, `{"filename": "logs/web.log", "maxlines":0,"maxsize":0,"daily":true,"maxdays":60}`)
		}
	} else {
		// 开发环境
		beego.SetLevel(beego.LevelDebug)
		beego.SetLogFuncCall(true)
	}

	return
}
